package algorithmic_data_structure.堆与堆排序;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeMap;

public class 比较器的用法 {
    static class Student{
        int age;
        String name;
        public Student(int age, String name) {
            this.age = age;
            this.name = name;
        }
        @Override
        public String toString() {
            return "Student{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    public static void main(String[] args){
        List<Student> list = new ArrayList<>();

        list.add(new Student(1,"abc"));
        list.add(new Student(3,"bac"));
        list.add(new Student(2,"dac"));
        list.add(new Student(2,"cab"));

        list.sort(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age - o2.age != 0 ? o1.age - o2.age : o1.name.compareTo(o2.name);
            }
        });
        list.forEach(System.out::println);

        //treemap的使用必须要指定比较器，否则会报错不知道如何进行排序
//        TreeMap<Student,String> treeMap = new TreeMap<>();
        TreeMap<Student,String> treeMap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age - o2.age != 0 ? o1.age - o2.age : o1.name.compareTo(o2.name);
            }
        });
        treeMap.put(new Student(1,"abc"),"一号");
        treeMap.put(new Student(3,"bac"),"二号");
        treeMap.put(new Student(2,"dac"),"三号");
        treeMap.put(new Student(2,"cab"),"四号");
        treeMap.entrySet().forEach(System.out::println);

    }
}
